﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace ControleEstoque.Entidades
{
	/**********************/
	/* Self explain class */
	/**********************/
	internal static class Misc
	{
		public static DateTime ConverHexToDate(string hex)
		{
			StringBuilder sb = new StringBuilder();

			for (int i = 0; i < hex.Length; i += 2)
			{
				sb.Append((char)byte.Parse(hex.Substring(i, 2), NumberStyles.HexNumber));
			}

			string originalData = sb.ToString();

			return new DateTime(int.Parse(originalData.Substring(0, 4)), int.Parse(originalData.Substring(4, 2)), int.Parse(originalData.Substring(6, 2)));
		}

		public static string PrintTag(byte[] tag, int size)
		{
			StringBuilder hex = new StringBuilder();
			for (int i = 0; i < size && i < tag.Length; i++)
			{
				hex.Append(Convert.ToString(tag[i], 16).PadLeft(2, '0'));
			}
			return hex.ToString();
		}
		public static bool Equals(byte[] barray1, byte[] barray2)
		{
			if (barray1.Length != barray2.Length)
				return false;
			for (int i = 0; i < barray1.Length; i++)
				if (barray1[i] != barray2[i])
					return false;
			return true;
		}
		public static bool IsHexDigit(char c)
		{
			int numChar;
			int numA = Convert.ToInt32('A');
			int num1 = Convert.ToInt32('0');
			c = Char.ToUpper(c);
			numChar = Convert.ToInt32(c);
			if (numChar >= numA && numChar < (numA + 6))
				return true;
			if (numChar >= num1 && numChar < (num1 + 10))
				return true;
			return false;
		}
		public static byte[] GetBytes(string hexString, int maxbasize)
		{
			int discarded = 0;
			string newString = "";
			char c;

			hexString = hexString.Replace(" ", "");
			if (hexString.Length % 2 != 0)
				hexString = "0" + hexString;
			for (int i = 0; i < hexString.Length; i++)
			{
				c = hexString[i];
				if (IsHexDigit(c) && i < (maxbasize * 2))
					newString += c;
				else
					discarded++;
			}
			if (newString.Length % 2 != 0)
			{
				discarded++;
				newString = newString.Substring(0, newString.Length - 1);
			}
			int byteLength = newString.Length / 2;
			byte[] bytes = new byte[byteLength];
			string hex;
			int j = 0;
			for (int i = 0; i < bytes.Length; i++)
			{
				hex = new String(new Char[] { newString[j], newString[j + 1] });
				bytes[i] = HexToByte(hex);
				j += 2;
			}
			return bytes;
		}
		private static byte HexToByte(string hex)
		{
			if (hex.Length > 2 || hex.Length <= 0)
				throw new ArgumentException("hex must be 1 or 2 characters in length");
			byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
			return newByte;
		}
	}
}
